package cn.iocoder.an.module.business.service.codelist;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.an.module.business.controller.admin.codelist.CodeParser;
import cn.iocoder.an.module.business.dal.dataobject.partlist.PartListDO;
import cn.iocoder.an.module.business.dal.mysql.partlist.PartListMapper;
import cn.iocoder.an.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import cn.iocoder.an.module.business.controller.admin.codelist.vo.*;
import cn.iocoder.an.module.business.dal.dataobject.codelist.CodeListDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.business.dal.mysql.codelist.CodeListMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.business.enums.ErrorCodeConstants.*;

/**
 * 编码信息 Service 实现类
 *
 * @author zzy
 */
@Service
@Validated
public class CodeListServiceImpl implements CodeListService {

    @Resource
    private CodeListMapper codeListMapper;

    @Resource
    private PartListMapper partListMapper;


    @Resource
    private AdminUserService adminUserService;

    @Override
    public Long createCodeList(CodeListSaveReqVO createReqVO) {
        // 插入
        CodeListDO codeList = BeanUtils.toBean(createReqVO, CodeListDO.class);
        //判断有无重复
//        checkCode(codeList);
        setData(codeList);
        codeListMapper.insert(codeList);

        // 返回
        return codeList.getId();
    }

    @Override
    public Long createFailCodeList(CodeListSaveReqVO createReqVO) {
        createReqVO.setFactoryInfo("未通过");
        CodeListDO codeListDo = BeanUtils.toBean(createReqVO, CodeListDO.class);
        String loginUserNickname = SecurityFrameworkUtils.getLoginUserNickname();
        codeListDo.setOperator(loginUserNickname);
        codeListMapper.insert(codeListDo);
        return 0L;
    }


    @Override
    public void updateCodeList(CodeListSaveReqVO updateReqVO) {
        // 校验存在
        validateCodeListExists(updateReqVO.getId());
        // 更新
        CodeListDO updateObj = BeanUtils.toBean(updateReqVO, CodeListDO.class);
//        checkCode(updateObj);
        setData(updateObj);
        codeListMapper.updateById(updateObj);
    }

    public void setData(CodeListDO codeListDo) {
        String code = codeListDo.getCode().trim();
        codeListDo.setCode(code);

        String loginUserNickname = SecurityFrameworkUtils.getLoginUserNickname();

        CodeParser.ParsedCode parse = CodeParser.parse(code);
        String partNumber = parse.getPartNumber();
        String supplierCode = parse.getSupplierCode();
        String batchInfo = parse.getBatchInfo();
        codeListDo.setPartNumber(partNumber);
        codeListDo.setPartUniqueCode(partNumber + supplierCode);
        codeListDo.setBatchInfo(batchInfo);
        codeListDo.setSupplyCode(supplierCode);

        codeListDo.setOperator(loginUserNickname);


    }


    public Map<String, Object> checkCode(CodeListDO codeListDo) {

        Map<String, Object> map = new HashMap<>();
        map.put("flag", true);
        map.put("message", "success");

        String code = codeListDo.getCode();

        String loginUserNickname = SecurityFrameworkUtils.getLoginUserNickname();

        CodeParser.ParsedCode parse = CodeParser.parse(code);
        String partNumber = parse.getPartNumber();
        String supplierCode = parse.getSupplierCode();
        String batchInfo = parse.getBatchInfo();
        codeListDo.setPartNumber(partNumber);
        codeListDo.setPartUniqueCode(partNumber + supplierCode);
        codeListDo.setBatchInfo(batchInfo);
        codeListDo.setSupplyCode(supplierCode);

        codeListDo.setOperator(loginUserNickname);

        //查询供应商代码

//        if (!"sdl0032".equalsIgnoreCase(supplierCode.trim())) {
//            map.put("flag", false);
//            map.put("message", "供应商代码错误: 解析到的值为: '" + supplierCode +
//                    "', 正确值应为: 'sdl0032'（不区分大小写，且不能有空格）");
//            return map;
//        } else if (supplierCode == null) {
//            map.put("flag", false);
//            map.put("message", "供应商代码错误: 解析到的值为: '" + supplierCode +
//                    "', 正确值应为: 'sdl0032'（不区分大小写，且不能有空格）");
//            return map;
//        }


        //判断零件号是否存在
        LambdaQueryWrapper<PartListDO> partListQueryWrapper = new LambdaQueryWrapper<>();
        partListQueryWrapper.eq(PartListDO::getPartNumber, partNumber);
        boolean exists = partListMapper.exists(partListQueryWrapper);
        if (!exists) {
            map.put("flag", false);
            map.put("message", "零件号:" + partNumber + "在零件号管理中不存在,请先在零件号管理中配置");
            return map;
        }


        LambdaQueryWrapper<CodeListDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CodeListDO::getCode, code.trim());
        if (codeListDo.getId() == null) {
            List<CodeListDO> codeListDOS = codeListMapper.selectList(queryWrapper);

            if (codeListDOS != null && codeListDOS.size() > 0) {
                String msg = "编码重复,已由" + codeListDOS.getFirst().getOperator() + "创建!";
                map.put("flag", false);
                map.put("message", msg);
                return map;
            }
        } else {
            //修改排除自身
            queryWrapper.ne(CodeListDO::getId, codeListDo.getId());
            List<CodeListDO> codeListDOS = codeListMapper.selectList(queryWrapper);
            if (codeListDOS != null && codeListDOS.size() > 0) {
                String msg = "编码重复,已由" + codeListDOS.getFirst().getOperator() + "创建!";
                map.put("flag", false);
                map.put("message", msg);
                return map;
            }
        }




        //校验

        return map;
    }

    @Override
    public void deleteCodeList(Long id) {
        // 校验存在
        validateCodeListExists(id);
        // 删除
        codeListMapper.deleteById(id);
    }

    @Override
    public void deleteCodeListListByIds(List<Long> ids) {
        // 删除
        codeListMapper.deleteByIds(ids);
    }


    private void validateCodeListExists(Long id) {
        if (codeListMapper.selectById(id) == null) {
            throw exception(CODE_LIST_NOT_EXISTS);
        }
    }

    @Override
    public CodeListDO getCodeList(Long id) {
        return codeListMapper.selectById(id);
    }

    @Override
    public PageResult<CodeListDO> getCodeListPage(CodeListPageReqVO pageReqVO) {
        return codeListMapper.selectPage(pageReqVO);
    }

}